﻿using System;
using System.Collections.Generic;
using System.Text;

namespace ExpressionUtil.Parser.Handler
{
    /// <summary>
    /// 变量处理程序
    /// </summary>
    internal class VariableHandler : ParseHandlerBase
    {
        /// <summary>
        /// 默认构造函数
        /// </summary>
        public VariableHandler()
        {
            this.next = null;
        }

        /// <summary>
        /// 解析元素
        /// </summary>
        /// <param name="context">解析参数</param>
        /// <param name="element">需要解析的元素</param>
        /// <returns>是否已解析</returns>
        protected override bool ParseCore(string element, ParseContext context)
        {
            bool ret = false;
            this.ParseVariable(element, context);
            context.IncreaseFunctionParameterCount();
            ret = true;
            return ret;
        }

        /// <summary>
        /// 解析变量
        /// </summary>
        /// <param name="variableName">变量名称</param>
        /// <param name="context">解析参数</param>
        private void ParseVariable(string variableName, ParseContext context)
        {
            if (context.Variables.ContainsKey(variableName))
            {
                Node.VariableNode variable = context.Variables[variableName];
                context.PostfixStack.Push(variable);
            }
            else
            {
                Node.VariableNode variable = new Node.VariableNode(variableName);
                context.PostfixStack.Push(variable);
                context.Variables.Add(variableName, variable);
            }
        }
    }
}
